package com.shallwead.bna.Async;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.RemoteViews;

import com.shallwead.bna.BnA;
import com.shallwead.bna.R;
import com.shallwead.bna.object.AdGcmMsg;
import com.shallwead.bna.util.Logger;

public class PushNotiAsync extends AsyncTask<String, String, Bitmap> {

	Context mContext;
	Bitmap bm;
	Notification notify;
	NotificationManager nm;

	public PushNotiAsync(Context mContext) {
		this.mContext = mContext;
	}

	@Override
	protected Bitmap doInBackground(String... params) {

		Bitmap bm = null;
		try {
			bm = getBitmap(BnA.gcmMsg.getImageUrl());
		} catch (Exception e) {
		}
		return bm;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		super.onPostExecute(result);
		if (result != null && BnA.gcmMsg != null) {
			send_noti(result, BnA.gcmMsg);
		}
	}

	void send_noti(Bitmap bitmap, AdGcmMsg gcmMsg) {
		nm = (NotificationManager) mContext.getApplicationContext()
				.getSystemService(Context.NOTIFICATION_SERVICE);
		notify = new Notification(R.drawable.googleplay_logo,
				gcmMsg.getContent(), System.currentTimeMillis());

		RemoteViews contentView = new RemoteViews(mContext.getPackageName(),
				R.layout.push_layout);
		contentView.setImageViewBitmap(R.id.main_image, bitmap);
		contentView.setTextViewText(R.id.message, gcmMsg.getContent());
		contentView.setTextViewText(R.id.title, gcmMsg.getTitle());
		notify.contentView = contentView;

		Intent notificationIntent = new Intent(mContext,
				com.shallwead.bna.service.PushNotiService.class);
		notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent contentIntent = PendingIntent.getService(mContext, 0,
				notificationIntent, 0);

		if ("IN".equals(gcmMsg.getDes())) {
			Logger.d(mContext.getPackageName());
			notificationIntent = mContext.getPackageManager()
					.getLaunchIntentForPackage(mContext.getPackageName());
			notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			contentIntent = PendingIntent.getActivity(mContext, 0,
					notificationIntent, 0);
		}
		notify.contentIntent = contentIntent;

		nm.notify(455444, notify);

	}

	public Bitmap getBitmap(String url) {
		Bitmap bm = null;
		try {
			URL aURL = new URL(url);
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
		} catch (IOException e) {

		}
		return bm;
	}
}